//题目:如下为类型 CMyString 的声明，请为该类型添加赋值运算符函数
// 心得:1. 输入参数的检查 2.借助临时变量，离开作用域，析构释放内存 3.构造函数 引用传递
#include <iostream>
#include <cstring>

class CMyString {
public:
    explicit CMyString(char *pdata = nullptr);

    virtual ~CMyString();

    CMyString(const CMyString &str);

    CMyString &operator=(const CMyString &str);

    void Print();

private:
    char *_pdata;
};

CMyString::CMyString(char *pdata) {
    if (pdata == nullptr) {
        _pdata = new char[1]();
    } else {
        int len = strlen(pdata);
        _pdata = new char[len + 1]();
        strcpy(_pdata, pdata);
    };
}

CMyString::~CMyString() {
    delete[] _pdata;
    _pdata = nullptr;
}

CMyString::CMyString(const CMyString &str) {
    int len = strlen(str._pdata);
    _pdata = new char[len + 1]();
    strcpy(_pdata, str._pdata);
}

CMyString &CMyString::operator=(const CMyString &str) {
    if (this != &str) {
        CMyString t(str);
        char *pt = _pdata;
        _pdata = t._pdata;
        t._pdata = pt;
    }
    return *this;
}

void CMyString::Print() {
    std::cout << _pdata << std::endl;
}

void Test1() {
    printf("Test1 begins:\n");

    char *text = "Hello world";

    CMyString str1(text);
    CMyString str2;
    str2 = str1;

    printf("The expected result is: %s.\n", text);

    printf("The actual result is: ");
    str2.Print();
    printf(".\n");
}

// 赋值给自己
void Test2() {
    printf("Test2 begins:\n");

    char *text = "Hello world";

    CMyString str1(text);
    str1 = str1;

    printf("The expected result is: %s.\n", text);

    printf("The actual result is: ");
    str1.Print();
    printf(".\n");
}

// 连续赋值
void Test3() {
    printf("Test3 begins:\n");

    char *text = "Hello world";

    CMyString str1(text);
    CMyString str2, str3;
    str3 = str2 = str1;

    printf("The expected result is: %s.\n", text);

    printf("The actual result is: ");
    str2.Print();
    printf(".\n");

    printf("The expected result is: %s.\n", text);

    printf("The actual result is: ");
    str3.Print();
    printf(".\n");
}

int main(int argc, char *argv[]) {
    Test1();
    Test2();
    Test3();

    return 0;
}